import storage from '@/utils/ado-self/ado-storage';
import { EMIT_PARAMS_OBJ } from '@/utils/constant';
import { isEmptyObject, objHas, visualAction } from '@/utils/util';
import { mapMutations } from 'vuex';
import { getComponentEmitConfig } from '../utils/emitComponentBaseUtil';
export default {
  data() {
    return {
      isStopRealData: false, // 是否暂停实时数据
      currentPageStatus: '',
      lastParams: null, // 上一次发出的参数，重新请求数据会清空
    };
  },
  methods: {
    ...mapMutations(['setComponentStatus', 'deleteComponentStatus']),

    // 获取共享参数的值 （只对发出组件有效）
    getSharedParameterValue(returnObj = false) {
      let value = '';
      let _foundValue = false;

      if (this.isSharedParameter) {
        const _eventKey = this.config.events[0].key;
        const _eventParameterKey = this.config.events[0].parameters[0].key;
        for (const key in this.pageStatus) {
          if (_foundValue) {
            continue;
          }
          if (key.includes(EMIT_PARAMS_OBJ)) {
            const { eventKey, isSharedParameter, parameters, widgetInstanceId, keys } = this.pageStatus[key];

            let eventParameterKey;
            let targetValue;

            // 新的发出事件 数据格式
            if (widgetInstanceId && keys && parameters) {
              // 目前该格式只支持单值，时间范围不适用
              eventParameterKey = keys.length && keys[0];
              targetValue = parameters[eventParameterKey];
            } else {
              // 使用旧的发出事件数据格式(没有widgetInstanceId或parameters)
              eventParameterKey = this.pageStatus[key].key;
              targetValue = this.pageStatus[_eventParameterKey];
            }

            if (isSharedParameter && String(_eventKey) === String(eventKey) && String(_eventParameterKey) === String(eventParameterKey)) {
              _foundValue = true;
              value = targetValue;
            }
          }
        }
      }

      if (returnObj) {
        return {
          found: _foundValue,
          value,
        };
      }

      return value;
    },

    getPageStatusParameterValue(pageStatus) {
      let value = '';

      const _eventKey = this.config.events[0].key;
      const _eventParameterKey = this.config.events[0].parameters[0].key;
      let _foundValue = false;
      for (const key in pageStatus) {
        if (_foundValue) {
          continue;
        }
        if (key.includes(EMIT_PARAMS_OBJ)) {
          const { eventKey, parameters, widgetInstanceId, keys } = pageStatus[key];

          let eventParameterKey;
          let targetValue;

          // 新的发出事件 数据格式
          if (widgetInstanceId && keys && parameters) {
            // 目前该格式只支持单值，时间范围不适用
            eventParameterKey = keys.length && keys[0];
            targetValue = parameters[eventParameterKey];
          } else {
            // 使用旧的发出事件数据格式(没有widgetInstanceId或parameters)
            eventParameterKey = pageStatus[key].key;
            targetValue = pageStatus[_eventParameterKey];
          }
          if (String(_eventKey) === String(eventKey) && String(_eventParameterKey) === String(eventParameterKey)) {
            _foundValue = true;
            value = targetValue;
          }
        }
      }
      return value;
    },

    getCurrentPageStatus() {
      const { pageId } = this;
      const { tenantId } = window._adoPremise;
      const pageStatus = storage.session.get(`${pageId}_${tenantId}`) || {};
      this.currentPageStatus = pageStatus;
    },
    _setComponentStatus(hasAsync) {
      this.setComponentStatus({
        pageId: this.pageId,
        widgetInstanceId: this.widgetInstanceId,
        hasAsync: hasAsync,
      });
    },

    // 将item与this.lastParams比对，index, key, value一致时视为true
    isSameParams({ item, index, key, value }) {
      let flag = false;
      if (!isEmptyObject(this.lastParams)) {
        if (
          String(index) === String(this.lastParams.index) &&
          String(item[key]) === String(this.lastParams[key]) &&
          String(item[value]) === String(this.lastParams[value])
        ) {
          flag = true;
        }
      }
      return flag;
    },

    // pie组件，与上一个发出的参数对比，是否同一个参数
    isSameParamsPie(params) {
      let flag = false;
      if (!isEmptyObject(this.lastParams)) {
        if (
          objHas(params, 'dataIndex') &&
          objHas(this.lastParams, 'dataIndex') &&
          String(params.dataIndex) === String(this.lastParams.dataIndex) &&
          String(params.name) === String(this.lastParams.name) &&
          String(params.value) === String(this.lastParams.value)
        ) {
          flag = true;
        }
      }
      return flag;
    },

    /**
     * 桑基图点击方法
     */
    chartClickSankey(params, data) {
      if (visualAction() === 'clickLegend') {
        return;
      }
      this.lastParams = params;
      this.bindLowCodeChartClickCallback(params);

      const outObj = {};
      const evtKey = this.orgConfig.events[0].key || 'chart-click';
      const { key } = this.orgConfig.events[0].parameters[0];
      const { paramKey } = this.config.events[0]; // 字段名code
      // 根据字段名传 params.name/params.value
      let tableData = [];
      tableData = this.config.config.data.tableData;
      const col = tableData.find(t => String(t.mapping) === String(paramKey));
      if (!col) {
        return;
      }
      if (objHas(params, 'value') && String(params.value) === '') {
        outObj[key] = params.value;
      } else {
        if (params.dataType === 'node') {
          // 块
          col.field !== 'value' ? (outObj[key] = params.data.name) : (outObj[key] = params.value);
        } else {
          // 线
          outObj[key] = this.actionConfig(params, col.field, paramKey, data);
        }
      }

      const keys = [this.config.events[0].parameters[0].key];
      const parameters = {
        [keys[0]]: outObj[key],
      };

      outObj[EMIT_PARAMS_OBJ] = {
        eventKey: this.config.events[0].key,
        keys,
        type: 'terms',
        parameters,
        widgetInstanceId: this.widgetInstanceId,
        sendTime: new Date().getTime(),
      };
      this.vsEmit(evtKey, outObj);
    },

    // 通用图表组件点击事件
    chartClick(params, data, isEmitNormalEvent = true) {
      if (visualAction() === 'clickLegend') {
        return;
      }
      this.lastParams = params;
      this.bindLowCodeChartClickCallback(params);
      if (!isEmitNormalEvent) {
        return;
      }

      const outObj = {};
      const evtKey = this.orgConfig.events[0].key || 'chart-click';
      const { key } = this.orgConfig.events[0].parameters[0];
      const { paramKey } = this.config.events[0]; // 字段名code
      // 根据字段名传 params.name/params.value
      let tableData = [];
      const { propertyPannelName } = this.config;
      if (propertyPannelName === `config_${process.env.xvueNameSpace_}table_gantt_chart`) {
        tableData = this.config.config.data.gantt.tableData;
      } else if (propertyPannelName === 'config_visual_common_x_multiple_y') {
        tableData = this.config.config.data.datas[0];
      } else {
        tableData = this.config.config.data.tableData;
      }
      const col = tableData.find(t => paramKey && String(t.mapping) === String(paramKey));
      if (!col) {
        return;
      }
      if (objHas(params, 'value') && String(params.value) === '') {
        outObj[key] = params.value;
      } else {
        outObj[key] = this.actionConfig(params, col.field, paramKey, data);
      }

      const keys = [this.config.events[0].parameters[0].key];
      const parameters = {
        [keys[0]]: outObj[key],
      };

      outObj[EMIT_PARAMS_OBJ] = {
        eventKey: this.config.events[0].key,
        type: 'terms',
        parameters,
        keys,
        widgetInstanceId: this.widgetInstanceId,
        sendTime: new Date().getTime(),
      };
      this.vsEmit(evtKey, outObj);
    },

    // 通用图标的鼠标事件
    chartMouse(isStop) {
      this.isStopRealData = isStop;
    },

    /**
     * 事件取值的方法
     */
    actionConfig(params, field, paramKey, data) {
      const config = {
        [`config_${process.env.xvueNameSpace_}gantt_chart`]: () => this.getGanttChartVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}table_gantt_chart`]: () => this.getGanttChartVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}sankey`]: () => this.getSankeyVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}uniaxial_line`]: () => this.getUniaxialLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}stacked_area`]: () => this.getUniaxialLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}uniaxial_bar`]: () => this.getUniaxialLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}single_biaxial_line_bar`]: () =>
          this.getUniaxialLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}biaxial_line_line`]: () => this.getUniaxialLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}biaxial_line_bar`]: () => this.getUniaxialLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}basic_pie`]: () => this.getPieChartValVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}rose_pie`]: () => this.getPieChartValVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}multidimensional_pie`]: () => this.getPieChartValVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}tree_map`]: () => this.getPieChartValVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}chain_comparison_indicator_bar`]: () =>
          this.getChainComparisonIndicatorBarVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}relationship_diagram`]: () =>
          this.getRelationshipDiagramVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}scatter`]: () => this.getScatterVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}k_line_config`]: () => this.getKLineVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}ladder_waterfall`]: () => this.getLadderWaterfallVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}heat_map`]: () => this.getHeatMapVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}shape_chart`]: () => this.getUniaxialLineVal(params, field, paramKey, data),
        'config_visual_common_x_multiple_y': () => this.getCommonXMultipleYVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}radar_chart`]: () => this.getRadarChartVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}funnel_chart`]: () => this.getFunnelChartVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}bubble_chart`]: () => this.getBubbleChartVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}dash_board`]: () => this.getDashBoardVal(params, field, paramKey, data),
        [`config_${process.env.xvueNameSpace_}chain_comparison_chart`]: () => this.getChainComparisonVal(params, field, paramKey, data),
      };
      const { propertyPannelName } = this.config;
      return config[propertyPannelName]();
    },

    getChainComparisonIndicatorBarVal(params, field, paramKey, data) {
      if (field === 's') {
        return params.data.name;
      } else {
        return params.data.value;
      }
    },
    getLadderWaterfallVal(params, field, paramKey, data) {
      if (field === 'x') {
        return params.name;
      } else {
        return params.data;
      }
    },

    getCommonXMultipleYVal(params, field, paramKey, data) {
      if (field === 'x') {
        return params.name;
      } else if (field === 'y1') {
        return params.value;
      } else {
        return params.seriesName;
      }
    },

    getPieChartValVal(params, field, paramKey, data) {
      const obj = getComponentEmitConfig(this.config.propertyPannelName);
      return params.data[obj[field]];
    },

    getUniaxialLineVal(params, field, paramKey, data) {
      if (field === 's') {
        return params.seriesName;
      } else if (field === 'x') {
        return params.name;
      } else {
        return params.data[1];
      }
    },

    getGanttChartVal(params, field, paramKey, data) {
      const obj = getComponentEmitConfig(this.config.propertyPannelName);
      return data[obj[field]][params.dataIndex];
    },

    getSankeyVal(params, field, paramKey, data) {
      return params.data[field];
    },

    getRelationshipDiagramVal(params, field, paramKey, data) {
      const obj = getComponentEmitConfig(this.config.propertyPannelName);
      return params.data[obj[field]];
    },

    getScatterVal(params, field, paramKey, data) {
      if (field === 's') {
        return params.seriesName;
      } else if (field === 'c') {
        return params.data[2];
      } else if (field === 'x') {
        return params.data[0];
      } else if (field === 'y') {
        return params.data[1];
      } else {
        return null;
      }
    },

    getChainComparisonVal(params, field, paramKey, data) {
      if (field === 's') {
        return params.name;
      } else if (field === 'y1') {
        return params.groupData[0].value;
      } else if (field === 'y2') {
        return params.groupData[1].value;
      } else if (field === 'y3') {
        return params.groupData[2].value;
      } else {
        return null;
      }
    },

    getKLineVal(params, field, paramKey, data) {
      if (field === 'x') {
        return params.name;
      } else if (field === 'y1') {
        return params.data.value[1];
      } else if (field === 'y2') {
        return params.data.value[2];
      } else if (field === 'y3') {
        return params.data.value[3];
      } else if (field === 'y4') {
        return params.data.value[4];
      } else {}
      return null;
    },

    getHeatMapVal(params, field, paramKey, data) {
      // 热图数据有时候有4个子项，有时候5个子项，用函数抓取
      function getColRowVal(_data, key) {
        const item = _data.find(n => typeof n === 'object' && objHas(n, key));
        const val = (item && item[key]) || '';
        return val;
      }

      if (field === 'row') {
        return getColRowVal(params.data, 'row');
      } else if (field === 'column') {
        return getColRowVal(params.data, 'column');
      } else if (field === 'value') {
        return params.data[2];
      } else {
        return null;
      }
    },
    getBubbleChartVal(params, field, paramKey, data) {
      if (field === 'source') {
        return params.data.source || params.name;
      } else if (field === 'target') {
        return params.name;
      } else if (field === 'value') {
        return params.value;
      } else if (field === 'unit') {
        return params.unit;
      } else {
        return null;
      }
    },
    getDashBoardVal(params, field, paramKey, data) {
      if (field === 'value') {
        return params.data.value;
      } else if (field === 'rank') {
        return params.data.rank;
      } else if (field === 'total') {
        return params.data.total;
      } else {}
      return null;
    },

    getRadarChartVal(params, field, paramKey, data) {
      function getVal(_data, key) {
        const item = Array.from(new Set(_data?.orgData?.map(n => n && n[key]))).filter(id=>id);
        const val = item && item[0];
        return val;
      }
      if (field === 's') {
        return params.name;
      } else if (field === 'name') {
        return getVal(params.data, field);
      } else if (field === 'y') {
        return getVal(params.data, field);
      } else if (field === 'unit') {
        return getVal(params.data, field);
      } else {
        return null;
      }
    },

    getFunnelChartVal(params, field, paramKey, data) {
      if (field === 's') {
        return params.name;
      } else if (field === 'y') {
        return params.value;
      } else if (field === 'unit') {
        return params.data.unit;
      } else {
        return null;
      }
    },

    // 在发出事件前对相同事件名，相同key的 共享参数对象的值做出修正
    beforeEmit(outObj) {
      if (!this.isSharedParameter) {
        return;
      }
      const sharedParameters = window._adoPremise.$sharedParameters;
      const emitParamsObj = outObj[EMIT_PARAMS_OBJ];
      for (const key in sharedParameters) {
        if (key.indexOf(EMIT_PARAMS_OBJ) <= -1) {
          continue;
        }
        const o = sharedParameters[key];
        if (
          o.componentName === emitParamsObj.componentName &&
          o.eventKey === emitParamsObj.eventKey &&
          o.keys.toLocaleString() === emitParamsObj.keys.toLocaleString()
        ) {
          o.parameters = emitParamsObj.parameters;
        }
      }
    },

    // 通用普通发送空事件
    sendEmptyMessages() {
      this.lastParams = null;
      const evtKey = this.orgConfig.events[0].key || 'row-click';
      const { key } = this.orgConfig.events[0].parameters[0];

      const outObj = { key: '' };
      const keys = [];
      const parameters = {};

      outObj[EMIT_PARAMS_OBJ] = {
        eventKey: this.config.events[0].key,
        type: 'terms',
        keys,
        parameters,
        widgetInstanceId: this.widgetInstanceId,
        componentName: this.config.propertyPannelName,
        sendTime: new Date().getTime(),
        isEmpty: true, // 空事件标记，使用可参考弹窗组件
      };
      this.vsEmit(evtKey, outObj);
    },

    // 通用普通发送事件
    sendAllMessages(item) {
      this.executeAction('', item);
      const evtKey = this.orgConfig.events[0].key || 'row-click';
      const outObj = {};
      const { key } = this.orgConfig.events[0].parameters[0];
      const { paramKey } = this.config.events[0]; // 字段名code
      const col = this.config.config.data.tableData.find(t => t.mapping === paramKey);
      if (!col) {
        return;
      }
      outObj[key] = item[col.field];

      const keys = [this.config.events[0].parameters[0].key];
      const parameters = {
        [keys[0]]: item[col.field],
      };

      outObj[EMIT_PARAMS_OBJ] = {
        eventKey: this.config.events[0].key,
        type: 'terms',
        keys,
        parameters,
        widgetInstanceId: this.widgetInstanceId,
        componentName: this.config.propertyPannelName,
        sendTime: new Date().getTime(),
      };
      this.vsEmit(evtKey, outObj);
    },

  },
  mounted() {
    this.getCurrentPageStatus();
  },
};
